#define  _CRT_SECURE_NO_WARNINGS 1
#include "slist.h"

SlistNode* BuySListNode(SLTNodeType x)
{
	SlistNode* pn = (SlistNode*)malloc(sizeof(SlistNode));
	if (pn == NULL)
	{
		perror("malloc");
		return NULL;
	}
	pn->data = x;
	pn->next = NULL;
	return pn;
}

void SlistNodePrint(SlistNode** phead)
{
	SlistNode* curr = *phead;
	while (curr)
	{
		printf("%d ", curr->data);
		curr = curr->next;
	}
	printf("\n");
}

void SlistNodeInsert(SlistNode** phead,  SlistNode* pos, SLTNodeType x)
{
	//assert(pos);

	SlistNode* newnode = BuySListNode(x);
	if (*phead == NULL)
	{
		*phead = newnode;
	}
	if (*phead == pos)
	{
		newnode->next = *phead;
		*phead = newnode;
	}
	else
	{
		SlistNode* curr = *phead;
		while (curr->next != pos)
		{
			curr = curr->next;
		}
		curr->next = newnode;
		newnode->next = pos;
	}

}


void SlistNodeErase(SlistNode** phead, SlistNode* pos)
{
	assert(*phead);
	assert(pos);
	if (*phead == pos)
	{
		*phead = (*phead)->next;
		free(pos);
	}
	else
	{
		SlistNode* curr = *phead;
		while (curr->next != pos)
		{
			curr = curr->next;
		}

		curr->next = pos->next;
		free(pos);
	}
	
}

void SlistNodePushBack(SlistNode** phead, SLTNodeType x)
{
	SlistNode* newnode = BuySListNode(x);
	SlistNode* curr = *phead;
	if (*phead == NULL)
	{
		*phead = newnode;
	}
	else
	{
		while (curr->next != NULL)
		{
			curr = curr->next;
		}
		curr->next = newnode;
	}
}

void SlistNodePushFront(SlistNode** phead, SLTNodeType x)
{
	SlistNode* newnode = BuySListNode(x);
	newnode->next = *phead;
	*phead = newnode;
}


void SlistNodePopFront(SlistNode** phead)
{
	assert(*phead);
	SlistNode* del = *phead;
	*phead = (*phead)->next;
	free(del);
}

void SlistNodePopBack(SlistNode** phead)
{
	assert(*phead);

	SlistNode* curr = *phead;
	SlistNode* prev = NULL;
	if (curr->next == NULL)
	{
		free(curr);
		*phead = NULL;
	}
	else
	{
		while (curr->next != NULL)
		{
			prev = curr;
			curr = curr->next;
		}
		prev->next = NULL;
		free(curr);
	}
}

SlistNode* SlistNodeFind(SlistNode** phead, SLTNodeType x)
{
	assert(*phead);

	SlistNode* curr = *phead;
	while (curr)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}